<?php
/**
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class EditSalesController extends AppController
{
    # Controller Name to be used
    var $name = 'EditSales';

    # Models to be used
    var $uses = array(
        'Sale',
        'Customer',
        'Item',
        'SaleCreditPayment'
    );

    # set the layout to use
    var $layout = 'editsales_layout';

    # set the name of this module
    var $moduleName = 'Edit Customers Sales';

    # Check the authenticity of the user
    function  beforeFilter(){
        parent::beforeFilter($this->moduleName);
        parent::setUpGlobalConfig();
    }

    # Controller actions
    /**
     * This function displays all the users in the system
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index(){

        $customers_sales = $this->get_customers_select();

        $currency_opts = $this->currency_types;
        $pay_type_opt = $this->payment_types;

        $page_title = 'Edit Sales';

        $this->set(compact('page_title','customers_sales','currency_opts','pay_type_opt'));
    }

    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function add(){
        # Get the user session data
        $loggedUser = $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch ($model) {
                case 'Sale' :
                    $loggedUser_id = $loggedUser['id'];

                    //$this->Sale->create();
                    $data = $_POST['data'];
                    $purchase_date = $data['Sale']['purchased_date'];
                    $months_duration = $data['Sale']['duration_in_month'];
                    $data['Sale']['purchased_date'] = date("Y-m-d",strtotime($purchase_date));
                    $data['Sale']['end_date'] = date("Y-m-d",strtotime(date("Y-m-d", strtotime($purchase_date)) . " +$months_duration month"));

                    //Re- calculate the principal
                    $new_cost =  $data['Sale']['cost'] + $data['Sale']['insurance_total'];
                    $bal = $this->getPrincipal($new_cost,$data['Sale']['discount'],$data['Sale']['deposit']);
                    $data['Sale']['principal'] = $bal;
                    $data['Sale']['opening_bal'] = $bal;
                    //debug($this->formatNumber($bal));
                    //debug($new_cost);
                   // debug($data['Sale']['deposit']);
                    if(floatval($this->formatNumber($bal)) <= '0.00' && "$new_cost" == floatval(trim($data['Sale']['deposit']))){
                        $data['Sale']['principal'] = $new_cost;
                        $data['Sale']['opening_bal'] = $new_cost;
                        $data['Sale']['on_credit'] = 'n';
                    }
                    $data['Sale']['modified_by'] = $loggedUser_id;
                    # save the data
                    if ($this->Sale->save($data)) {

                        return json_encode(array('code' => 0, 'data' => $data, 'mesg' => __('Data Saved')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => $this->Sale->invalidFields()));
                    }
                    break;
            }
        }
    }


    function loadSale(){
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        $sale = $this->Sale->find('first',array(
            'conditions'=>array('Sale.id'=>$_POST['data-id']),
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name','Customer.contact_person'),
                ),
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount'),
                )
            ),
            'recursive'=> 2
        ));

        if($sale){
            return json_encode(array('code' => 0, 'data' => $sale, 'mesg' => __('Data Found')));
        }
        else{
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    /**
     * @name get
     * @param void
     * @return Json Data
     */
    function get(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;
        /* Get Customer Id for filtering */
        $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;

        $condition_array = array('Sale.deleted'=>'n');
        if($customer_id > 0){
            $condition_array['Sale.customer_id'] = $customer_id;
        }

        //$fields = array('Customer.id','Customer.name');
        $data = $this->Sale->find('all', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit'),
            'conditions' => $condition_array,
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name','Customer.contact_person'),
                ),
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount'),
                )
            ),
            'order' => "Sale.$sortname $sortorder",
            'limit' => $start . ',' . $limit,
            'recursive' => 2
        ));
        $dataCount = $this->Sale->find('count', array(
            'conditions' => $condition_array,
            'recursive' => -1
        ));

        $total_records = $dataCount;

        if ($data) {
            $return_arr = array();
            foreach ($data as $obj) {

                $duration_in_month = $obj['Sale']['duration_in_month'];
                $currency = $obj['Sale']['currency'];
                $opening_bal = doubleval($obj['Sale']['opening_bal']);

                $purchase_type = $obj['Sale']['purchase_type'];
                $mth_inst = $this->getMonthlyPayment($obj['Sale']['interest'],$duration_in_month, $opening_bal, $obj['Sale']['tenor'],$obj['Sale']['interest_rate_decimal_places'],$purchase_type);

                //$discount_amt =  (doubleval($obj['Sale']['discount']) / 100) * doubleval($obj['Sale']['principal']);
                $deposite = doubleval($obj['Sale']['deposit']);

                //Total Creidt Payment
                $totalpayment = 0.00;
                foreach ($obj['SaleCreditPayment'] as $data) {
                    $totalpayment += doubleval($data['paid_amount']);
                }

                // Outstanding balance
                $bal = (doubleval($obj['Sale']['opening_bal']) - $totalpayment);

                $items = '';
                foreach ($obj['SaleItem'] as $item) {
                    //$items .= $item['Item']['name'] . '(qty x' . $item['quantity'] . '),&nbsp;&nbsp;';
                    $items .= $item['Item']['name'].'&nbsp;&nbsp;';
                }

                $return_arr[] = array(
                    'id' => $obj['Sale']['id'],
                    'cell' => array(
                        $obj['Sale']['id'],
                        $obj['Sale']['purchased_date'],
                        $obj['Customer']['name'],
                        $obj['Sale']['invoice_number'],
                        $obj['Sale']['vehicle_no'],
                        $items,
                        $currency.' '.$this->formatNumber($obj['Sale']['cost'],'money'),
                        $obj['Sale']['interest'],
                        $duration_in_month . ' Month(s)',
                        /*
                        ,*/
                        //$obj['Sale']['end_date'],
                        //$currency.' '.$this->formatNumber($obj['Sale']['opening_bal'],'money'),
                        /*,*/
                        /*$this->formatNumber($obj['Sale']['discount']),
                        $this->formatNumber($deposite,'money'),*/
                        //$currency.' '.$this->formatNumber($mth_inst,'money'),
                        //$currency.' '.$this->formatNumber($totalpayment,'money'),
                        //$currency.' '. $this->formatNumber($bal,'money')
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }


    function delete_(){
        if($this->request->is('ajax')){
            $this->autoRender = false;
            $this->autoLayout = false;

            $loggedUser =  $this->Auth->user();
            $loggedUser_id = $loggedUser['id'];

            $ids = $_POST['ids'];
            $modObj = ClassRegistry::init('Sale');
            $result = $modObj->updateAll(
                array('Sale.deleted' => "'y'",'Sale.modified_by' => $loggedUser_id ),
                array('Sale.id' => $ids)
            );

            if($result){
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Item(s) have been successfully deleted')));
            }
            else{
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Item(s) cannot be deleted')));
            }
        }
    }



    /**
     * @name get
     * @param void
     * @return Json Data
     */
   /* function getRepayment(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        $page =      isset($_POST['page']) ? $_POST['page'] : 1 ;
        $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ;
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ;
        $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ;
        $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ;
        $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
        $limit = $rp;
        $start = ($page-1) * $rp;

        $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;


        $condition_array = array('SaleCreditPayment.deleted' => 'n');

        if (!empty($search_query)){
            if($search_query == 'name'){
                $condition_array = array(
                    'SaleCreditPayment.name LIKE' => $search_query . '%',
                    'SaleCreditPayment.deleted' => 'n'
                );
            }
            else{
                $condition_array = array(
                    "SaleCreditPayment.$qtype LIKE" => $search_query . '%',
                    'SaleCreditPayment.deleted' => 'n'
                );
            }
        }

        //if($customer_id > 0){
          //  $condition_array['Sale.customer_id'] = $customer_id;
        //}


        $fields = array('SaleCreditPayment.id','SaleCreditPayment.sale_id','SaleCreditPayment.paid_amount','SaleCreditPayment.pay_date','SaleCreditPayment.pay_type','SaleCreditPayment.comments');
        $users = $this->SaleCreditPayment->find('all', array('fields'=>$fields,'conditions' => $condition_array,'order' => "SaleCreditPayment.$sortname $sortorder",'limit' => $start.','.$limit,'recursive' => -1));
        $usersCount  = $this->SaleCreditPayment->find('count', array('conditions' => $condition_array,'recursive' => -1));

        $total_records = $usersCount;

        if($users){
            $return_arr = array();
            foreach ($users as $obj){

                $sale = $this->Sale->find('first',array(
                    'fields'=>array('Sale.id','Sale.customer_id'),
                    'conditions'=>array('Sale.id'=>$obj['SaleCreditPayment']['sale_id']),
                    'contain'=>array('Customer'=>array(
                        'fields'=>array('Customer.id','Customer.name')
                    )),
                    'recursive'=>1
                ));

                $return_arr[] = array(
                    'id' => $obj['SaleCreditPayment']['id'],
                    'cell' => array(
                        $obj['SaleCreditPayment']['id'],
                        $sale['Customer']['name'],
                        $this->formatMoney($obj['SaleCreditPayment']['paid_amount']),
                        $obj['SaleCreditPayment']['pay_date'],
                        $obj['SaleCreditPayment']['pay_type'],
                        $obj['SaleCreditPayment']['comments']
                    )
                );
            }
            return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
        }
        else{
            return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
        }

    }*/


    function getRepayment(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;
        $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;

        /* $condition_array = array('Sale.on_credit'=>'y');
        if (!empty($search_query)){
            if($search_query == 'name'){
                $condition_array = array(
                    'Customer.name LIKE' => $search_query . '%',
                    'Sale.on_credit'=>'y'
                );
            }
        }*/

        $condition_array = array('Sale.deleted'=>'n');
        if($customer_id > 0){
            $condition_array['Sale.customer_id'] = $customer_id;
        }

        //$fields = array('Customer.id','Customer.name');
        $data = $this->Sale->find('all', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit'),
            'conditions' => $condition_array,
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name'),
                ),
                'SaleItem' => array(
                    'fields' => array('SaleItem.item_id'),
                    'Item' => array(
                        'fields' => array('Item.name')
                    )
                ),
                'SaleCreditPayment' => array(
                    'fields' => array('SaleCreditPayment.paid_amount'),
                )
            ),
            'order' => "Sale.$sortname $sortorder",
            'limit' => $start . ',' . $limit,
            'recursive' => 2
        ));
        $dataCount = $this->Sale->find('count', array(
            'conditions' => $condition_array,
            'recursive' => -1
        ));

        $total_records = $dataCount;

        //echo debug($users);

        if ($data) {
            $return_arr = array();
            foreach ($data as $obj) {

                $duration_in_month = $obj['Sale']['duration_in_month'];
                $currency = $obj['Sale']['currency'];
                $opening_bal = doubleval($obj['Sale']['opening_bal']);

                $purchase_type = $obj['Sale']['purchase_type'];
                $mth_inst = $this->getMonthlyPayment($obj['Sale']['interest'],$duration_in_month, $opening_bal, $obj['Sale']['tenor'],$obj['Sale']['interest_rate_decimal_places'],$purchase_type);

                //$discount_amt =  (doubleval($obj['Sale']['discount']) / 100) * doubleval($obj['Sale']['principal']);
                $deposite = doubleval($obj['Sale']['deposit']);

                //Total Creidt Payment
                $totalpayment = 0.00;
                foreach ($obj['SaleCreditPayment'] as $data) {
                    $totalpayment += doubleval($data['paid_amount']);
                }

                // Outstanding balance
                $bal = (doubleval($obj['Sale']['opening_bal']) - $totalpayment);

                $return_arr[] = array(
                    'id' => $obj['Sale']['id'],
                    'cell' => array(
                        $obj['Sale']['id'],
                        $obj['Sale']['purchased_date'],
                        $obj['Customer']['name'],
                        $obj['Sale']['invoice_number'],
                        $obj['Sale']['vehicle_no'],
                        /*
                        $duration_in_month . ' Month(s)',*/
                        //$obj['Sale']['end_date'],
                        $currency.' '.$this->formatNumber($obj['Sale']['opening_bal'],'money'),
                        /* $this->formatNumber($obj['Sale']['principal'],'money'),*/
                        /*$this->formatNumber($obj['Sale']['discount']),
                        $this->formatNumber($deposite,'money'),*/
                        $currency.' '.$this->formatNumber($mth_inst,'money'),
                        $currency.' '.$this->formatNumber($totalpayment,'money'),
                        $currency.' '. $this->formatNumber($bal,'money')
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }


    /**
     *
     * @param void
     * @return html
     * @access public
     */
    function repayment(){
        $creditors = $creditors_data_r = $this->Sale->find('all', array(
            'conditions' => array('Sale.on_credit' => 'y'),
            'contain' => array(
                'Customer' => array(
                    'fields' => array('Customer.id', 'Customer.name'),
                ),
                'SaleItem' => array(
                    'Item'
                ),
                'SaleCreditPayment'
            ),
            'order' => array('Sale.id' => 'desc'),
            'recursive' => 2
        ));

        $creditors = Set::combine($creditors, '{n}.Customer.id', '{n}.Customer.name');

        $creditors_data = array();
        foreach ($creditors_data_r as $key => $data) {
            $customer_id = $data['Customer']['id'];
            $sale_id = $data['Sale']['id'];
            $data['Sale']['SaleItem'] = $data['SaleItem'];
            $data['Sale']['SaleCreditPayment'] = $data['SaleCreditPayment'];

            /*$d1 = $data['Sale']['purchased_date']; //Smaller date
            $d2 = $data['Sale']['end_date']; //Bigger date
            $data['Sale']['duration_in_month'] = $this->count_months_between_dates($d1, $d2);*/

            if ($data['Sale']['SaleCreditPayment']) {
                $last_dt = $data['Sale']['SaleCreditPayment'][0]['pay_date']; // this is sorted on id desc, so the first index[0] is the last paid date
            }
            else {
                $last_dt = $data['Sale']['purchased_date'];
            }
            //$d = new DateTime($last_dt);
            //$d->modify('next month');

            $data['Sale']['last_paid_date'] = $last_dt;
            $data['Sale']['next_credit_date'] = date("Y-m-d",strtotime(date("Y-m-d", strtotime($last_dt)) . " +1 month"));

            $creditors_data[$customer_id]['Customer'] = $data['Customer'];
            $creditors_data[$customer_id]['Sale'][$sale_id] = $data['Sale'];

        }

        $pay_type_opt = $this->payment_types;

        $this->set(compact('pay_type_opt', 'creditors', 'creditors_data'));

    }


    function edit_repayment(){

        $customers_sales = $this->get_customers_select();

        $currency_opts = $this->currency_types;
        $pay_type_opt = $this->payment_types;

        $page_title = 'Edit Repayment';

        $this->set(compact('page_title','pay_type_opt','currency_opts','customers_sales'));
    }


    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function updateRepayment(){
        # Get the user session data
        $loggedUser =  $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if($this->request->is('ajax')){
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch($model){
                case 'SaleCreditPayment' :
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $loggedUser_id = $loggedUser['id'];

                    $this->request->data['SaleCreditPayment']['pay_date'] = date("Y-m-d",strtotime($this->request->data['SaleCreditPayment']['pay_date']));

                    $this->SaleCreditPayment->id = $upt_id;

                    $this->request->data['SaleCreditPayment']['modified_by'] = $loggedUser_id;

                    # save the data
                    if($this->SaleCreditPayment->save($this->request->data)){
                        return json_encode(array('code' => 0, 'mesg' => __('Data Saved')));
                    }
                    else{
                        return json_encode(array('code' => 1, 'mesg' => $this->SaleCreditPayment->invalidFields()));
                    }
                    break;
            }
        }
    }


    /**
     *
     * @param void
     * @return html
     * @access public
     */
    function loadRepayment(){
        $this->autoRender = false;
        $this->autoLayout = false;


        $condition_array = array('Sale.id'=>$_POST['data-id']);

        //$fields = array('Customer.id','Customer.name');
        $data = $this->Sale->find('first', array(
            //'fields' => array('Sale.id', 'Sale.customer_id', 'Sale.purchased_date', 'Sale.end_date', 'Sale.cost', 'Sale.deposit'),
            'conditions' => $condition_array,
            'contain' => array(
                'SaleCreditPayment' => array(
                    'conditions' => array('SaleCreditPayment.deleted'=>'n'),
                )
            ),
            'recursive' => 1
        ));

        //echo debug($data);


        /** Loading */
        //$userData = $this->Item->getById($_POST['data-id']);
        /*$sale_repayment = $this->SaleCreditPayment->find('first',array(
            'conditions'=>array('SaleCreditPayment.id'=>$_POST['data-id']),
            'recursive'=>-1
        ));*/


        if($data){
            return json_encode(array('code' => 0, 'data' => $data, 'mesg' => __('Data Found')));
        }
        else{
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }

    #
    function delete_Repayment(){
        if($this->request->is('ajax')){
            $this->autoRender = false;
            $this->autoLayout = false;

            $loggedUser = $this->Auth->user();
            $loggedUser_id = $loggedUser['id'];

            $ids = $_POST['ids'];
            $modObj = ClassRegistry::init('SaleCreditPayment');
            $result = $modObj->updateAll(
                array('SaleCreditPayment.deleted' => "'y'" ,'SaleCreditPayment.modified_by' => $loggedUser_id),
                array('SaleCreditPayment.id' => $ids)
            );

            if($result){
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Item(s) have been successfully deleted')));
            }
            else{
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Item(s) cannot be deleted')));
            }
        }
    }

}

?>
